<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_from" :model="loginForm" :rules="rules" ref="loginFormRef">
          <el-form-item prop="logo"><el-link type="primary" :underline="false">(^_^)</el-link></el-form-item>
          <el-form-item prop="title"><el-link type="primary" :underline="false">深圳引望智能技术有限公司</el-link></el-form-item>
          <el-form-item prop="username"><el-input :prefix-icon="User" v-model="loginForm.username"></el-input></el-form-item>
          <el-form-item prop="password"><el-input :prefix-icon="Lock" type="password" show-password v-model="loginForm.password"></el-input></el-form-item>
          <el-form-item prop="operation"><el-button :loading="loading" :disabled="disabled" class="login_btn" type="primary" icon="User" @click="userLoginPiniaApiRequest">登录</el-button></el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from "@element-plus/icons-vue";
import { reactive, ref } from "vue";
import { ElNotification, FormInstance, FormRules } from "element-plus";

// 00.表单对象Ref
let loginFormRef = ref<FormInstance>();

// 01.表单对象
let loginForm = reactive({
  username: "admin",
  password: "111111",
});

// 02.表单校验
// let rules = {
//   username: [
//     {
//       required: true,
//       max: 12,
//       min: 5,
//       message: "用户名不能小于5或超过12个字母或数字",
//       trigger: ["blur", "change"],
//     },
//   ],
//   password: [
//     {
//       required: true,
//       max: 15,
//       min: 6,
//       message: "用户名不能超过12个字母或数字",
//       trigger: ["blur", "change"],
//     },
//   ],
// };

// 02.自定义表单校验
let validatorUsername = (rule: any, value: any, callback: any) => {
  // console.log('账号校验规则:', rule);
  if (!value) {
    return callback(new Error("账号是必填项"));
  }
  setTimeout(() => {
    if (!value) {
      callback(new Error("账号是必填项"));
    } else {
      if (value.length < 5) {
        callback(new Error("账号必须大于五位"));
      }
      if (value.length > 18) {
        callback(new Error("账号不能大于十八位"));
      }
      callback();
    }
  }, 1000);
};
let validatorPassword = (rule: any, value: any, callback: any) => {
  // console.log('密码校验规则:', rule);
  if (value === "") {
    callback(new Error("Please input the password"));
  } else {
    if (loginForm.password !== "") {
      if (!loginFormRef.value) return;
      loginFormRef.value.validateField("checkPass");
    }
    callback();
  }
};
let rules = reactive<FormRules<typeof loginForm>>({
  username: [
    {
      validator: validatorUsername,
      trigger: ["blur", "change"],
    },
  ],
  password: [
    {
      validator: validatorPassword,
      trigger: ["blur", "change"],
    },
  ],
});

// 03.表单接口
import { useRoute, useRouter } from "vue-router";
import { getTimeStr } from "@/utils/common";
import useUserStore from "@/store/modules/user";
let userStore = useUserStore();
// 路由对象
let $route = useRoute();
// 路由器对象
let $router = useRouter();
// 加载状态
let loading = ref(false);
// 禁用状态
let disabled = ref(false);
// 登录接口Api
let userLoginPiniaApiRequest = async () => {
  loading.value = true;
  disabled.value = true;
  console.log('表单对象Ref1:', loginFormRef.value);
  console.log('表单对象Ref2:', loginFormRef.value?.validate);
  console.log('表单对象Ref3:', loginFormRef.value?.validate());
  console.log('表单对象1:', loginForm);
  // 正确示范
  let a = await loginFormRef.value?.validate();
  console.log("校验结果a:", a);
  // 正确示范
  let b = await loginFormRef.value?.validate((valid) => {
    if (valid) {
      console.log('校验已通过b:', valid);
    } else {
      console.log('校验不通过b:', valid);
    }
  });
  console.log("校验结果b:", b);
  // 正确示范
  let c = await loginFormRef.value?.validate((arg0: boolean) => {
    if (arg0) {
      console.log("校验已通过c:", arg0);
    } else {
      console.log("校验不通过c:", arg0);
    }
  });
  console.log("校验结果c:", c);
  // 错误示范(没有增加 await 字段!异步,所有信息执行完成,才会执行打印)
  let d = loginFormRef.value?.validate((arg0: boolean) => {
    if (arg0) {
      console.log('校验已通过d:', arg0);
    } else {
      console.log('校验不通过d:', arg0);
    }
  });
  console.log("校验结果d:", d);
  let headers = {
    "Content-Type": "application/json", // JSON格式
  };
  await userStore.userLoginAction(loginForm, headers)
    .then((res) => {
      console.log("Api [return] data:", res);
      if (res.code === 200) {
        let flag = $route.query.redirect;
        console.log('带了路径的哟:', flag);
        if (flag) {
          $router.push({ path: flag });
        } else {
          $router.push({ path: "/" });
        }
        ElNotification({ type: "success", title: res.data, message: getTimeStr() });
        loading.value = false;
        disabled.value = false;
      }
    })
    .catch((err) => {
      ElNotification({ type: "error", title: "登录失败", message: err.message });
      loading.value = false;
      disabled.value = false;
    });
};
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background-color: slategrey;
  background-image: url("@/assets/images/background.jpg");
  background-size: cover;
}
.login_from {
  position: relative;
  width: 60%;
  top: 30vh;
  background-image: url("@/assets/images/login_form.png");
  background-size: cover;
  padding: 40px;
  .el-link {
    font-size: 20px;
    color: white;
  }
  .login_btn {
    width: 100%;
  }
}
</style>
